﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Security;
using Texfina.Core.Common;

namespace Texfina.ERP
{
   public partial class wfLogin : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {

      }

      private void AutenticateUser(string domainName, string userName, string password)
      {
         string adPath = "LDAP://" + ConfigurationManager.AppSettings[ConstSistema.APSET_AD_LDAP];

         ActiveDirectoryValidator adAuth = new ActiveDirectoryValidator(adPath);

         if (adAuth.IsAuthenticated(domainName, userName, password))
         {
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, "");

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            HttpContext.Current.Response.Cookies.Add(authCookie);

            Response.Redirect("Default.aspx");
         }
      }


      protected void bttLogin_Click(object sender, EventArgs e)
      {
         string strDomain = ConfigurationManager.AppSettings[ConstSistema.APSET_AD_DOMAIN];

         try
         {
            AutenticateUser(strDomain, this.txtUsername.Text, this.txtPassword.Text);
         }
         catch (Exception ex)
         {
            errorLabel.Text = ex.Message;
            errorLabel.Visible = true;
         }

      }
   }
}